<!--
 * @Author: zhang00001 774004514@qq.com
 * @Date: 2024-06-17 10:18:04
 * @LastEditors: zhang00001 774004514@qq.com
 * @LastEditTime: 2024-08-02 16:18:17
 * @FilePath: \vue-admin\src\pages\active\ActivityForm.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <a-drawer
      :title="activeId ? '编辑' : '新增'"
      placement="right"
      :maskClosable="false"
      :keyboard="false"
      @close="showAddDialog = false"
      width="800"
      v-model:open="showAddDialog"
    >
      <a-form
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        ref="formRef"
        :rules="rules"
        :model="formData"
        label-position="top"
      >
        <a-form-item
          label="活动名称"
          required
          name="title"
        >
          <a-input v-model:value="formData.title"></a-input>
        </a-form-item>
        <a-form-item
          label="活动图片"
          required
          name="image"
        >
          <ImageUpload
            ref="uploadRef"
            :limit="1"
            :fileSize="1"
            v-model:modelValue="formData.image"
          ></ImageUpload>
        </a-form-item>
        <a-form-item
          label="活动价格"
          required
          name="price"
        >
          <a-input-number
            id="inputNumber"
            v-model:value="formData.price"
            :min="0"
            :max="10000000"
          />
        </a-form-item>

        <a-form-item
          label="活动时间"
          required
          name="activity_time"
        >
          <a-date-picker show-time
            v-model:value="formData.activity_time"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </a-form-item>

        <a-form-item 
          label="报名开始时间"
          required
          name="start"
        >
          <a-date-picker show-time
            v-model:value="formData.start"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </a-form-item>

        <a-form-item
          label="报名截至时间"
          required
          name="deadline"
        >
          <a-date-picker show-time
            v-model:value="formData.deadline"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </a-form-item>
        <a-form-item
          label="可参与用户"
          required
          name="condition"
        >
          <a-radio-group v-model:value="formData.condition">
            <a-radio :value="0">普通用户</a-radio>
            <a-radio :value="8">vip用户</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="活动经纬度"
          required
          name="longitude"
        >
          <a-tooltip content="请点击查找位置选择位置">
            <div style="display: flex; align-items: center; justify-content: flex-start">
              <a-input
                style="width: 300px"
                v-model:value="formData.longitude"
                placeholder="请查找位置"
                class="dialogWidth"
                readOnly
              ></a-input>
              <a-button
                slot="append"
                @click="onSearch"
              >
                查找位置
              </a-button>
            </div>
          </a-tooltip>
        </a-form-item>
        <a-form-item
          label="活动地址"
          required
          name="address"
        >
          <a-textarea
            v-model:value="formData.address"
            placeholder="请输入活动地址"
            class="dialogWidth"
            :auto-size="{ minRows: 2, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>

        <a-form-item
          label="是否发布"
          required
          name="is_destroy"
        >
          <a-switch v-model:checked="formData.is_destroy" />
        </a-form-item>
        <a-form-item
          label="活动排序"
          required
          name="sort"
        >
          <a-input-number
            id="inputNumber"
            v-model:value="formData.sort"
            :min="0"
            :max="10000000"
          />
        </a-form-item>
        <a-form-item
          label="活动详细信息"
          required
          name="content"
        >
          <Editor
            v-model:modelValue="formData.content"
            :min-height="192"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button @click="showAddDialog = false">取消</a-button>
          <a-button
            style="margin-left: 20px"
            @click="previewEditDialog"
          >
            预览活动详细信息
          </a-button>

          <a-button
            type="primary"
            style="margin-left: 20px"
            @click="handleSubmit"
            :loading="loading"
          >
            确认
          </a-button>
        </a-form-item>
      </a-form>
      <previewEditor ref="previewEditorEle"></previewEditor>
      <a-form-item></a-form-item>
    </a-drawer>
    <a-modal
      v-model:open="modalMap"
      title="上传经纬度"
      append-to-body
      class="mapBox"
      width="500px"
    >
      <div style="height: 640px">
        <iframe
          id="mapPage"
          width="100%"
          height="100%"
          frameborder="0"
          v-bind:src="keyUrl"
        ></iframe>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
  import { extractImageUrls, deleteMultiples } from '@/utils/power.js'
  import { message } from 'ant-design-vue'
  import config from '@/config/index.js'
  import previewEditor from '@/components/previewEditor.vue'
  import { activeAdd, activeUpdate, adminDelTag } from '@/api/index.js'
  import { ref, defineEmits, defineExpose, defineProps, toRefs, nextTick, reactive, onMounted } from 'vue'
  import Collect from 'collect.js'
  const emits = defineEmits(['activity-added', 'close'])
  const props = defineProps({})
  const showAddDialog = ref(false)
  const formRef = ref()
  const keyUrl = ref('')
  const rules = {
    title: [
      {
        required: true,
        message: '请输入活动名称',
        trigger: 'change'
      },
      {
        min: 2,
        max: 50,
        message: '长度2-50字',
        trigger: 'blur'
      }
    ],

    sort: [
      {
        required: true,
        message: '请输入活动排序',
        trigger: 'change'
      }
    ],
    image: [
      {
        required: true,
        message: '请上传活动主图',
        trigger: 'change'
      }
    ],
    start: [
      {
        required: true,
        message: '请输入活动报名开始时间',
        trigger: 'change'
      }
    ],

    activity_time: [
      {
        required: true,
        message: '请输入活动时间',
        trigger: 'change'
      }
    ],
    deadline: [
      {
        required: true,
        message: '请输入活动报名截至时间',
        trigger: 'change'
      }
    ],
    content: [
      {
        required: true,
        message: '请输入活动详情',
        trigger: 'blur'
      }
    ]
  }
  const loading = ref(false)
  const formData = ref({
    condition: 0,
    is_destroy: false,
    image: '',
    sort: 99
  })
  const modalMap = ref(false)
  const onSearch = () => {
    modalMap.value = true
  }
  const previewEditorEle = ref(null)
  const previewEditDialog = () => {
    previewEditorEle.value.init(formData.value.content)
  }

  // 选择经纬度
  const selectAdderss = (data) => {
    //       cityname
    // :
    // "武汉市"
    // latlng
    // :
    // {lat: 30.502539296162844, lng: 114.36312936523437}
    // module
    // :
    // "locationPicker"
    // poiaddress
    // :
    // "湖北省武汉市洪山区浅水湾路"
    // poiname
    // :
    // "洪山区泉盛花园(浅水湾路南150米)"
    // this.ruleForm.latitude ="114.61070216015625,30.46765100000001"

    formData.value.address = data.poiaddress + '-' + data.poiname
    formData.value.longitude = data.latlng.lat + ',' + data.latlng.lng
    modalMap.value = false
  }
  // key值
  const getKey = () => {
    let keys = 'RGSBZ-OBYWL-E4APJ-MNODN-EOZK2-WFFQG' // res.tengxun_map_key;//
    keyUrl.value = `https://apis.map.qq.com/tools/locpicker?type=1&key=${keys}&referer=myapp`
  }

  onMounted(() => {
    getKey()
    window.addEventListener(
      'message',
      function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data
        if (loc && loc.module === 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          window.parent.selectAdderss(loc)
        }
      },
      false
    )
    window.selectAdderss = selectAdderss
  })
  const uploadVisible = ref(false)
  const handleSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        loading.value = true

        let http = activeId.value ? activeUpdate : activeAdd
        let params
 
        if (activeId.value) {
          const collection = Collect(formData.value)

          const diff = collection.diffAssoc(dateRow.value)

          if (diff.items.content) {
            const imageUrls = extractImageUrls(diff.items.content)

            //  已经删除的图
            const delArrImages = Collect(richImage.value).diff(imageUrls).all()
            // 新增的图
            const newArrImages = Collect(imageUrls).diff(richImage.value).all()
            if(newArrImages.length>0){
              adminDelTag({ img: newArrImages })
            }
           
            if (delArrImages && delArrImages.length > 0) {
              deleteMultiples(delArrImages)
            }
          }
          params = {
            activity_id: formData.value.activity_id,
            ...diff.all()
          }
           
          if (Object.values(params).length == 1) {
            message.error('暂未修改')
            return
          }
        } else {
          params = formData.value
          const imageUrls = extractImageUrls(formData.value.content)
          debugger
          if (imageUrls.length > 0) {
            adminDelTag({ img: imageUrls })
          }
        }
        params.price = formData.value.price * 100

        http(params)
          .then((res) => {
            if (res.errorCode) {
              message.error(res.msg || '操作失败')
              return
            }
            if (res.code == 200) {
              message.success('操作成功！')
              showAddDialog.value = false
              emits('activity-added')
            }
          })
          .catch((err) => {
            message.error(err.msg)
          })
          .finally(() => {
            loading.value = false
          })
      })
      .catch((error) => {
        console.log('error', error)
      })

    setTimeout(() => {
      loading.value = false
    }, 5000)
  }

  const dateRow = ref()
  const activeId = ref(null)
  const richImage = ref(null)
  const init = (row) => {
    showAddDialog.value = true
    nextTick(() => {
      formRef.value.resetFields()
      if (row) {
        activeId.value = row.activity_id
        dateRow.value = JSON.parse(JSON.stringify(row))
        formData.value = JSON.parse(JSON.stringify(row))
        formData.value.price = row.price / 100
        richImage.value = extractImageUrls(row.content)
      } else {
        formData.value.activity_id = null
        formData.value.sort = 99
        activeId.value = null
        formData.value.image = config.baseImg
      }
    })
  }
  defineExpose({
    init
  })
</script>

<style scoped></style>
